<template>
  <div style="padding: 10px; margin-bottom: 50px">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>聊天室</el-breadcrumb-item>
      <el-breadcrumb-item>聊天</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <!--用户列表-->
      <el-col :span="4">
        <el-card style="width: 150px; color: #333">
          <el-select v-model="userValue" placeholder="请选择">
            <el-option
              v-for="item in userOptions"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-card>
        <el-card style="width: 150px; height: 400px; color: #333" class="card">
          <div style="padding: 10px 0" v-for="user in userValue" :key="user.username">
            <span>{{ user.name }}</span>
            <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 16px; cursor: pointer"
               @click="chat(user)"></i>
            <span style="font-size: 12px;color: limegreen; margin-left: 5px"
                  v-if="user.id === chatUser.id">chatting...</span>
          </div>
        </el-card>
      </el-col>
      <!--聊天内容-->
      <el-col :span="20">
        <div style="width: 800px; margin: 0 auto; background-color: white;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc">
          <div style="text-align: center; line-height: 50px;">
            Web聊天室（{{ chatUser.name }}）
          </div>
          <div ref="chatMessageRef" style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="content"></div>
          <div style="height: 200px">
            <textarea v-model="text" style="height: 160px; width: 760px; padding: 20px; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: none"></textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="send">发送</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>

let socket;
export default {
  name: "Chat",
  data() {
    return {
      // 当前用户的信息
      user: {},
      isCollapse: false,
      // 所有在线用户
      users: {},
      // 正在聊天的用户
      chatUser: '',
      // 聊天数据
      text: "",
      // 前端聊天记录
      messages: [],
      // 后端聊天记录
      chats: [],
      // 聊天记录的html
      content: '',
      // 用户选择器
      userOptions: [],
      userValue: ''
    }
  },
  created() {
    this.init()
  },
  methods: {
    // 发送消息
    send() {
      if (!this.chatUser) {
        this.$message({type: 'warning', message: "请选择聊天对象"})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容"})
      } else {
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
          this.$message.error("发送消息失败，您的浏览器不支持WebSocket")
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "1", "to": "2", "text": "聊天文本"}
          let message = {to: this.chatUser.id, text: this.text}
          socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
          this.messages.push({user: this.user.name, text: this.text})
          // 构建消息内容，本人消息
          this.createContent(null, this.user.name, this.text)
          this.text = '';
        }
      }
    },
    // 将json的聊天消息数据转换成html
    createContent(remoteUser, nowUser, text) {
      let html
      // 当前用户消息
      if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
          "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
          "    <div class=\"tip left\" style=\"max-width: 500px; word-break: break-word; text-align: left\" >" + text + "</div>\n" +
          "  </div>\n" +
          "  <div class=\"el-col el-col-2\">\n" +
          "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
          "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
          "  </span>\n" +
          "  </div>\n" +
          "</div>";
      } else if (remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
          "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
          "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
          "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
          "  </span>\n" +
          "  </div>\n" +
          "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
          "    <div class=\"tip right\" style=\"max-width: 500px; word-break: break-word; text-align: left\">" + text + "</div>\n" +
          "  </div>\n" +
          "</div>";
      }
      // console.log(html)
      this.content += html;
      this.updateScroll()
    },
    // 建立websocket链接
    init() {
      this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
      let id = this.user.id;
      let _this = this;
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
        this.$message.error("您的浏览器不支持WebSocket")
      } else {
        console.log("聊天室加载失败，您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8888/chat/" + id;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          // console.log(msg)
          // console.log("收到数据====" + msg.data)
          let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"studentUsers": [{"id": "1","name": "张三"}],"coachUsers": [],"managerUsers": [],"onlineUsers": []}
          // console.log(data)
          if (data.onlineUsers) {  // 获取人员信息
            _this.userOptions = []
            _this.users.onlineUsers = data.onlineUsers.filter(user => user.id !== id)  // 获取用户信息，并且排除自身，自己不会出现在自己的聊天列表里
            _this.userOptions.push({label: '在线用户', value: _this.users.onlineUsers})
            _this.users.managerUsers = data.managerUsers.filter(user => user.id !== id)
            _this.userOptions.push({label: '经理', value: _this.users.managerUsers})
            _this.users.coachUsers = data.coachUsers.filter(user => user.id !== id)
            _this.userOptions.push({label: '教练', value: _this.users.coachUsers})
            _this.users.studentUsers = data.studentUsers.filter(user => user.id !== id)
            _this.userOptions.push({label: '学员', value: _this.users.studentUsers})

          } else if (data.from) {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            if (data.from === _this.chatUser.id) {
              _this.messages.push(data)
              // console.log("构建消息内容")
              // 构建消息内容
              _this.createContent(data.name, null, data.text)
            }
          } else {
            // console.log("错误")
            console.log(data)
            this.$message.error(data)
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
      }
    },

    // 初始化聊天记录
    chat(user) {
      this.chatUser = user
      this.content = ''
      this.$http.get('/driver/chat/chatRecords', {
        params: {
          id: user.id
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.chats = res.data.data
          this.chats.forEach(chat => {
            if (chat.initiator === user.id) {
              this.createContent(user.name, null, chat.message)
            } else if (chat.receiver === user.id) {
              this.createContent(null, user.name, chat.message)
            } else {
              console.log("聊天数据异常：")
              console.log(chat)
            }
          })
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(err.message)
      })
    },

    updateScroll() {
      this.$nextTick(() => {
        this.$refs.chatMessageRef.scrollTop = this.$refs.chatMessageRef.scrollHeight
      })



    }

  }
}
</script>
<style>
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width: auto;
  display: inline-block !important;
  display: inline;
}

.right {
  background-color: #cccccc;
  color: black;
}

.left {
  background-color: deepskyblue;
}

.card {
  overflow-y: auto /* 开启滚动显示溢出内容 */
}

</style>
